<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Chat Interface</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f4;
        }

        #chat {
            border: 1px solid #ccc;
            padding: 10px;
            height: 300px;
            overflow-y: scroll;
            background-color: white;
        }

        #messageInput {
            width: 80%;
            padding: 10px;
        }

        #sendButton {
            padding: 10px;
        }
    </style>
</head>

<body>
    <div id="chat"></div>
    <input type="text" id="messageInput" placeholder="Type your message here..." />
    <button id="sendButton">Send</button>

    <script>
        const chatDiv = document.getElementById('chat');
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');

        sendButton.onclick = function () {
            const message = messageInput.value;
            if (message) {
                const eventSource = new EventSource('http://localhost:8080/chat?message=' + message);
                eventSource.onmessage = function (event) {
                    if (event.data.indexOf("DONE") !== -1) {
                        eventSource.close();
                    }
                    const messageDom = document.createElement('span');
                    messageDom.textContent = event.data;
                    chatDiv.appendChild(messageDom);
                    chatDiv.scrollTop = chatDiv.scrollHeight; // Scroll to the bottom
                };

                eventSource.onerror = function (event) {
                    eventSource.close();
                    console.error('EventSource failed:', event);
                };

                console.log('Sending message:', message);
                const messageDom = document.createElement('div');
                messageDom.textContent = message;
                chatDiv.appendChild(messageDom);
                messageInput.value = ''; // Clear the input
            }
        };
    </script>
</body>

</html>